<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * 文件上传服务类
 * 
 * 职责：
 * - 处理文件上传相关的业务逻辑
 * - 图片上传、文件验证
 * - 生成唯一文件名
 * - 按年月组织目录结构
 */
class UploadService extends BaseService
{
    /**
     * 上传图片
     * 
     * @param UploadedFile $file 上传的文件
     * @param User $user 用户
     * @param string $directory 目录前缀，默认为 'authors'
     * @return array 包含 url, path, name 的数组
     * @throws \Illuminate\Validation\ValidationException
     */
    public function uploadImage(UploadedFile $file, User $user, string $directory = 'authors'): array
    {
        // 验证文件
        $validated = validator([
            'image' => $file
        ], [
            'image' => 'required|image|max:2048|mimes:jpeg,png,jpg,gif',
        ])->validate();

        // 生成唯一的文件名
        $fileName = Str::random(40) . '.' . $file->getClientOriginalExtension();
        
        // 按照年月组织目录结构：authors/{user_id}/{Y/m}/{filename}
        $path = $file->storeAs(
            "{$directory}/{$user->id}/" . date('Y/m'),
            $fileName,
            'public'
        );

        $url = Storage::url($path);
        
        return [
            'url' => $url,
            'path' => $path,
            'name' => $file->getClientOriginalName()
        ];
    }
}

